package com.kapo.egroup.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.kapo.egroup.common.CacheConstants;
import com.kapo.egroup.common.ResponseEnum;
import com.kapo.egroup.security.domain.LoginResult;
import com.kapo.egroup.security.domain.LoginUser;
import com.kapo.egroup.utils.JwtUtils;
import com.kapo.egroup.utils.RedisCache;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Title LoginSuccessHandler
 * @Description TODO
 * @Author 黄家宝
 * @Date 2022-10-13 02:04
 **/
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        //获取当前登录用户
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();

        //生成token
        String token = jwtUtils.generateToken(loginUser);
        //设置token签名密钥及过期时间
        long expireTime = Jwts.parser()//获取DefaultJwtParser
                .setSigningKey(jwtUtils.getSecret())//设置签名的密钥
                .parseClaimsJws(token.replace("jwt_",""))
                .getBody().getExpiration().getTime();//获取token过期时间

        //把生成的token存到redis
        //存进redis单纯利用了redis的过期时间
        //TODO 利用redis提高权限查找速率
        String tokenKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        redisCache.set(tokenKey,token,jwtUtils.getExpireTime()/1000);

        LoginResult loginResult = new LoginResult(loginUser.getUserId(), ResponseEnum.SUCCESS.getCode(),token,expireTime);

        String result = JSON.toJSONString(loginResult, SerializerFeature.DisableCircularReferenceDetect);
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
